package sim

import (
	"context"
	"errors"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/sagoo-cloud/sagooiot/internal/consts"
	"github.com/sagoo-cloud/sagooiot/internal/dao"
	"github.com/sagoo-cloud/sagooiot/internal/model"
	"github.com/sagoo-cloud/sagooiot/internal/service"
)

type sSimSimFactory struct{}

func sSimSimFactoryNew() *sSimSimFactory {
	return &sSimSimFactory{}
}
func init() {
	service.RegisterSimSimFactory(sSimSimFactoryNew())
}

// GetSimFactoryList 获取列表数据
func (s *sSimSimFactory) GetSimFactoryList(ctx context.Context, in *model.GetSimFactoryListInput) (total, page int, list []*model.SimFactoryOutput, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.SimFactory.Ctx(ctx)
		if in.KeyWord != "" {
			m = m.WhereLike(dao.SimFactory.Columns().Name, in.KeyWord)
		}
		total, err = m.Count()
		if err != nil {
			err = gerror.New("获取总行数失败")
			return
		}
		page = in.PageNum
		if in.PageSize == 0 {
			in.PageSize = consts.PageSize
		}
		err = m.Page(page, in.PageSize).Order("created_at desc").Scan(&list)
		if err != nil {
			err = gerror.New("获取数据失败")
		}
	})
	return
}

// GetSimFactoryById 获取指定ID数据
func (s *sSimSimFactory) GetSimFactoryById(ctx context.Context, id int) (out *model.SimFactoryOutput, err error) {
	err = dao.SimFactory.Ctx(ctx).Where(dao.SimFactory.Columns().Id, id).Scan(&out)
	return
}

// GetSimFactoryByType 获取appKey appSecret
func (s *sSimSimFactory) GetSimFactoryByType(ctx context.Context, types int) (out *model.SimFactoryOutput, err error) {
	err = dao.SimFactory.Ctx(ctx).Where(dao.SimFactory.Columns().Types, types).Where("status=1").Scan(&out)
	return
}

// AddSimFactory 添加数据
func (s *sSimSimFactory) AddSimFactory(ctx context.Context, in model.SimFactoryAddInput) (err error) {
	total, err := dao.SimFactory.Ctx(ctx).Where(dao.SimFactory.Columns().Types, in.Types).Count()
	if err != nil {
		return
	}
	if total > 0 {
		err = errors.New("只能添加一个账号")
		return
	}
	_, err = dao.SimFactory.Ctx(ctx).Insert(in)
	return
}

// EditSimFactory 修改数据
func (s *sSimSimFactory) EditSimFactory(ctx context.Context, in model.SimFactoryEditInput) (err error) {
	dao.SimFactory.Ctx(ctx).FieldsEx(dao.SimFactory.Columns().Id).Where(dao.SimFactory.Columns().Id, in.Id).Update(in)
	return
}

// DeleteSimFactory 删除数据
func (s *sSimSimFactory) DeleteSimFactory(ctx context.Context, Ids []int) (err error) {
	_, err = dao.SimFactory.Ctx(ctx).Delete(dao.SimFactory.Columns().Id+" in (?)", Ids)
	return
}

// SetStatusSimFactory 设置厂商状态
func (u *sSimSimFactory) SetStatusSimFactory(ctx context.Context, id, status int) (err error) {
	_, err = dao.SimFactory.Ctx(ctx).Where(dao.SimFactory.Columns().Id, id).Data(g.Map{"status": status}).Update()
	return
}
